package com.bro.person.admin.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * @author swallow
 * Created by swallow on 2018/11/19.<br>
 */
public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 用户请求request head对应的方式 如ajax
     */
    private static final String X_REQUEST_WITH = "x-requested-with";

    /**
     * ajax 请求标识 XMLHttpRequest.equals(request.getHeader("x-requested-with")) == true 表示 ajax request
     */
    private static final String XML_HTTP_REQUEST = "XMLHttpRequest";

    /**
     * 判断用户请求是否是ajax请求 应用场景 用户如果是ajax 请求 错误提示或者跳转信息为 json对象或者字符串 否者返回document
     * @param request 用户请求封装类
     * @return 返回信息判断 true 表示用户 ajax请求
     */
    public static boolean isAjaxRequest(HttpServletRequest request){
        logger.debug("[HttpUtils][isAjaxRequest] entering request:{},x-requested-with:{}",request,request.getHeader(X_REQUEST_WITH));
        boolean isAjaxRequest = false;
        if(!StringUtils.isBlank(request.getHeader(X_REQUEST_WITH)) && XML_HTTP_REQUEST.equals(request.getHeader(X_REQUEST_WITH))){
            isAjaxRequest = true;
        }
        logger.info("[HttpUtils][isAjaxRequest] desc request:{},x-requested-with:{},isAjaxRequest:{}",request,request.getHeader(X_REQUEST_WITH),isAjaxRequest);
        return isAjaxRequest;
    }

}
